package product.type;

import jodd.bean.BeanCopy;
import models.BaseModel;
import models.constants.AvailableStatus;
import models.constants.DeletedStatus;
import models.merchant.Merchant;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import play.modules.paginate.JPAExtPaginator;
import product.Product;
import product.ProductTypes;
import util.common.ConvertUtil;

import javax.persistence.*;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by buhaoba on 16/6/13.
 */
@Entity
@Table(name = "product_type")
public class ProductType extends BaseModel {

    /**
     * 类别名称
     */
    @Column(name = "name")
    public String name;

    /**
     * 排序号
     */
    @Column(name = "sort")
    public Integer sort;

    /**
     * 逻辑删除,0:未删除，1:已删除
     */
    @Enumerated(EnumType.ORDINAL)
    public DeletedStatus deleted;

    /**
     * 备注
     */
    @Column(name = "remark")
    public String remark;

    //类型对应图片
    @Column(name="image")
    public String image;


    /**
     * 商户信息
     */
    @JoinColumn(name = "merchant_id")
    @ManyToOne
    public Merchant merchant;

    @Transient
    public List<Product> productList;

    /**
     * Update
     * @param id
     * @param newObject
     */
    public static void update(Long id, ProductType newObject) {
        ProductType productType= ProductType.findById(id);
        BeanCopy.beans(newObject, productType).ignoreNulls(true).copy();
        productType.save();
    }

    /**
     * 分页查询.
     */
    public static JPAExtPaginator<ProductType> findByCondition(Map<String, Object> conditionMap, String orderByExpress, int pageNumber, int pageSize) {
        StringBuilder xsqlBuilder = new StringBuilder("t.deleted=models.constants.DeletedStatus.UN_DELETED ")
                .append("/~ and t.name like {name} ~/");
        util.xsql.XsqlBuilder.XsqlFilterResult result = new util.xsql.XsqlBuilder().generateHql(xsqlBuilder.toString(), conditionMap);
        JPAExtPaginator<ProductType> orderPage = new JPAExtPaginator<ProductType>("ProductType t", "t", ProductType.class,
                result.getXsql(), conditionMap).orderBy(orderByExpress);
        orderPage.setPageNumber(pageNumber);
        orderPage.setPageSize(pageSize);
        orderPage.setBoundaryControlsEnabled(false);
        return orderPage;
    }
    public ProductType() {}
    public ProductType(String name) {
        this.createAt = new Date();
        this.deleted = DeletedStatus.UN_DELETED;
    }

    /**
     * 根据层级查找产品类型
     * @return
     */
    public static List<ProductType> findAllProductTypes(){
        return find("deleted = ?  order by sort asc", DeletedStatus.UN_DELETED).fetch();
    }

    /**
     * 根据层级查找产品类型
     * @return
     */
    public static List<ProductType> findProductTypeByLevel(Integer level){
        return find("deleted = ? and status = ? and level = ? order by sort",DeletedStatus.UN_DELETED,AvailableStatus.AVAILABLE,level).fetch();
    }

    /**
     * 查看可用 类别
     *
     * @return
     */
    public static List<ProductType> findAvailable() {
        return find("deleted = ? and status = ? order by sort asc", DeletedStatus.UN_DELETED, AvailableStatus.AVAILABLE).fetch();
    }

    /**
     * 根据类别查看
     *
     * @return
     */
    public static List<ProductType> findAvailable(AvailableStatus status) {
        return find("deleted = ? and status = ? order by sort asc ", DeletedStatus.UN_DELETED, status).fetch();
    }

    /**
     * 加载产品类型树
     *
     * @return
     */
    public static List<ProductType> loadTypeTree(Long id, long productId) {
        Query query = em().createNativeQuery
                ("SELECT distinct t.id,t.sort,t.parent_type_id as parentTypeId,t.name,case when p.id is null " +
                        "THEN 0 else 1 end as 'isCheck',t.level,t.is_leaf as isLeaf ,t.status,case " +
                        "when is_leaf = 1 then 'open' else 'closed' end as 'state'  " +
                        "from product_type t LEFT JOIN product_types p ON t.id = p.type_id and p.product_id = " +
                        productId + " where t.deleted = 0 and t.status = 'AVAILABLE' and t.parent_type_id = " + id + "" +
                        " order by t.sort asc,id DESC ");
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        return query.getResultList();
    }


    /**
     * 加载可用的一级节点
     *
     * @return
     */
    public static List<ProductType> findChildNode(long id) {
        return ProductType.find(" parentTypeId = ? and status = ? and deleted = ? order by sort asc", id, AvailableStatus.AVAILABLE, DeletedStatus.UN_DELETED).fetch();
    }

    //根据ID删除操作明细
    public static void delByIds(Long[] delItemArray) {
        if (delItemArray != null) {
            for (Long typeId : delItemArray) {
                ProductType productType = ProductType.findById(typeId);
                productType.deleted = DeletedStatus.DELETED;
                productType.save();
            }
        }
    }


    /**
     * 判断productType是否被使用
     */
    public static String checkIsUsed(Long[] delItemArray) {
        String str = "销售类型:";
        if (delItemArray != null) {
            for (long typeId : delItemArray) {
                boolean check = ProductTypes.count(" type.id=? and deleted=?", typeId, DeletedStatus.UN_DELETED) > 0;
                if (check) {
                    ProductType productType = ProductType.findById(typeId);
                    str += ConvertUtil.toString(productType.name) + ",";
                }
            }
        }
        return str;
    }

    /**
     * 判断productType是否被使用
     */
    public static Boolean checkIsUsed(long typeId) {
       return Product.count("productType.id = ? and deleted = ? " , typeId , DeletedStatus.UN_DELETED) > 0 ;
    }


    /**
     * 查询类型树
     */
    public static List<Map> loadProductTypeTree(long id) {
        String sqlSelect = "Select id,name as 'text',node_id_path,is_leaf,remark,case when is_leaf = 1 then 'open' else 'closed' end as 'state' from product_type where deleted=0 and parent_type_id =" + id;
        Query query = ProductType.em().createNativeQuery(sqlSelect);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        return query.getResultList();
    }


    /**
     * 获取商品分类,且分类下有产品
     * @param merchatId
     * @return
     */
    public static List<Map<String , Object>> loadBeUsedType(long merchatId){
        String sqlSelect = "select * from product_type a where a.id in (" +
                "    select a.product_type_id from products a where a.deleted = 0 and a.merchant_id = "+merchatId+"  group by a.product_type_id " +
                "    )";

        Query query = ProductType.em().createNativeQuery(sqlSelect);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map<String , Object>> resultList = query.getResultList();
        return resultList ;
    }

    public static List<ProductType> loadAllType(){
        return ProductType.find(" deleted = ? " ,  DeletedStatus.UN_DELETED).fetch();
    }

    /**
     * 根据Id查询分类
     * @param id
     * @return
     */
    public static ProductType findByTypeId(long id){
        return ProductType.find("deleted = ? and id = ?" , DeletedStatus.UN_DELETED , id).first();
    }

}
